var app = getApp();
Page({
	data: {
		Lang: app.Lang,
		type: 0,
		comments: {
			page: 1,
			psize: 15,
			loaded: false,
			empty: false,
			data: []
		},
		replyDialog: false,
		replyContent: '',
	},

	onLoad: function (options) {
		var that = this;
		that.onPullDownRefresh();
		return;
	},

	onChangeType: function(e) {
		var that = this;
		var type = e.currentTarget.dataset.type;
		if(type == that.data.type) {
			return false;
		}
		that.setData({
			type: type,
			comments: {
				page: 1,
				psize: 15,
				loaded: false,
				empty: false,
				data: []
			}
		});
		that.onReachBottom();
	},

	onShowReplyDialog: function(e) {
		var that = this;
		that.setData({
			replyDialog: !that.data.replyDialog
		})
		if(e && e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.id) {
			that.setData({
				commentId: e.currentTarget.dataset.id
			});
		}
	},

	onConfirmReply: function() {
		var that = this;
		app.util.request({
			url: 'manage/service/comment/reply',
			data: {
				id: that.data.commentId,
				reply: that.data.replyContent,
			},
			success: function(res) {
				var result = res.data.message;
				if(result.errno) {
					app.util.toast(result.message);
					return;
				}
				app.util.toast('回复成功');
				that.setData({
					replyIndex: '',
				})
				that.onShowReplyDialog()
				that.onPullDownRefresh();
			}
		})
	},

	onSelectReply: function(e) {
		var that = this;
		var index = e.currentTarget.dataset.index;
		that.setData({
			replyIndex: index,
			replyContent: that.data.store.comment_reply[index]
		});
	},

	onGetTextarea: function(e) {
		var that =  this;
		that.setData({
			replyContent: e.detail.value
		})
	},

	onPullDownRefresh: function () {
		var that = this;
		that.setData({
			type: 0,
			comments: {
				page: 1,
				psize: 15,
				loaded: false,
				empty: false,
				data: []
			},
			replyDialog: false,
			replyContent: '',
		});
		that.onReachBottom();
		wx.stopPullDownRefresh();
	},

	onReachBottom: function () {
		var that = this;
		if(that.data.comments.loaded) {
			return false;
		}
		app.util.request({
			url: 'manage/service/comment',
			data: {
				type: that.data.type,
				page: that.data.comments.page,
				psize: that.data.comments.psize,
			},
			success: function(res) {
				var result = res.data.message;
				if(result.errno) {
					app.util.toast(result.message);
					return;
				}
				result = result.message;
				var comments = that.data.comments.data.concat(result.comments);
				that.data.comments.data = comments;
				that.data.comments.page++;
				if(!comments.length) {
					that.data.comments.empty = true;
				}
				if(result.comments.length < that.data.comments.psize) {
					that.data.comments.loaded = true;
				}
				that.setData({
					comments: that.data.comments,
					store: result.store
				})
			}
		})
	},

	onJsEvent: function(e) {
		app.util.jsEvent(e);
	},

	onShowImage: function(event) {
		app.util.showImage(event);
	}
})